<!-- 文章编辑页 -->
<template>
  <div class="article-edit">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑文章' : '发布文章' }}</h2>
    </div>

    <div class="edit-form">
      <el-form 
        ref="formRef"
        :model="articleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="articleForm.title"
            placeholder="请输入文章标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="封面">
          <el-upload
            class="cover-upload"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="uploadImage"
          >
            <el-image
              v-if="articleForm.coverImage"
              :src="getImageUrl(articleForm.coverImage)"
              class="cover-preview"
              fit="cover"
            />
            <el-button v-else type="primary">
              上传封面图片
            </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="articleForm.content"
            type="textarea"
            :rows="15"
            placeholder="请输入文章内容"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '保存' : '发布' }}
          </el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const submitting = ref(false)

const isEdit = computed(() => route.name === 'EditArticle')

const articleForm = ref({
  title: '',
  content: '',
  coverImage: ''
})

const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 获取文章详情
const fetchArticle = async () => {
  try {
    const res = await request.get(`/article/${route.params.id}`)
    if (res.data) {
      articleForm.value = {
        title: res.data.title,
        content: res.data.content,
        coverImage: res.data.coverImage
      }
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
    router.push('/community/list')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      const method = isEdit.value ? 'put' : 'post'
      const data = { ...articleForm.value }
      if (isEdit.value) {
        data.id = route.params.id
      }
      
      const res = await request[method]('/article', data)
      if (res.code === 200) {
        ElMessage.success(isEdit.value ? '文章已更新' : '文章已发布')
        router.push('/community/list')
      }
    } catch (error) {
      console.error('保存文章失败:', error)
      ElMessage.error('保存文章失败')
    } finally {
      submitting.value = false
    }
  })
}

// 上传图片前的验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const uploadImage = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    
    const res = await request.post('/file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.code === 200) {
      // 构建完整的图片访问URL
      const imageUrl = `${import.meta.env.VITE_API_URL}/file/download/${res.data}`
      // 保存文件名，用于提交表单
      articleForm.value.coverImage = res.data
      ElMessage.success('上传成功')
      options.onSuccess(imageUrl)
    } else {
      options.onError()
      ElMessage.error(res.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    options.onError()
    ElMessage.error('上传图片失败')
  }
}

// 计算图片完整URL
const getImageUrl = (fileName) => {
  if (!fileName) return ''
  return `${import.meta.env.VITE_API_URL}/api/file/download/${fileName}`
}

const cancel = () => {
  router.back()
}

onMounted(() => {
  if (isEdit.value) {
    fetchArticle()
  }
})
</script>

<style scoped>
.article-edit {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.edit-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.cover-upload {
  display: flex;
  justify-content: center;
}

.cover-preview {
  width: 100%;
  height: 200px;
  border-radius: 4px;
}

:deep(.el-upload) {
  width: 100%;
}
</style> 